package com.simplemall.account.service.impl;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.simplemall.account.dal.UserMapper;
import com.simplemall.account.dal.WxAccountMapper;
import com.simplemall.account.service.WxAccountService;
import com.simplemall.micro.serv.common.bean.account.User;
import com.simplemall.micro.serv.common.bean.account.WxAccount;
import com.simplemall.micro.serv.common.dto.account.WxRegisterDto;

@Service
public class WxAccountServiceImpl implements WxAccountService {

	
	private Logger logger = LoggerFactory.getLogger(WxAccountServiceImpl.class);

	@Autowired
	UserMapper userMapper;
	
	@Autowired
	WxAccountMapper wxAccountMapper;
	
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public boolean createWxAccount(String userJsonStr) {
		JSONObject jsonObject = null;
		try {
			if (StringUtils.isEmpty(userJsonStr)) {
				//mock data to generate order data
				return false;
			}
			jsonObject = JSONObject.parseObject(userJsonStr);
		} catch (Exception exception) {
			logger.error("用户数据解析异常{}", exception);
			return false;
		}
		WxRegisterDto wxRegisterDto = JSONObject.toJavaObject(jsonObject, WxRegisterDto.class);
		User user = new User(wxRegisterDto);
		String userid = getUserid();
		user.setUserid(userid);
		int userResutl = userMapper.insertSelective(user);
		WxAccount wxAccount = new WxAccount(wxRegisterDto);
		wxAccount.setUserid(userid);
		int wxResutl = wxAccountMapper.insertSelective(wxAccount);
		return userResutl >= 1 && wxResutl >=1 ? true : false ;
	}
	
	private String getUserid(){
		int count = 1;
		Integer userid = null;
		while(true){
			User user = userMapper.selectLastUser();
			userid = Integer.parseInt(user.getUserid());
			userid++;
			count = userMapper.countByUserid(userid+"");
			if(count == 0)
				break;
		}
		return userid+"";
	}

	@Override
	public WxAccount getWxAccountInfo(String openid) {
		return wxAccountMapper.selectByOpenid(openid);
	}

	@Override
	public boolean updateWxAccount(String userJsonStr) {
		JSONObject jsonObject = null;
		try {
			if (StringUtils.isEmpty(userJsonStr)) {
				//mock data to generate order data
				return false;
			}
			jsonObject = JSONObject.parseObject(userJsonStr);
		} catch (Exception exception) {
			logger.error("用户数据解析异常{}", exception);
			return false;
		}
		WxAccount wxAccount = JSONObject.toJavaObject(jsonObject, WxAccount.class);
		return wxAccountMapper.updateByPrimaryKeySelective(wxAccount) > 1 ? true : false;
	}

}
